<?php
namespace Weibo\Controller;
use Org\Util\PinYin;
use Weibo\Controller\WeibobaseController;

/**
 * 微博用户控制器
 * @author	Baiyu	2016-12-23
 */
class UserController extends WeibobaseController {
	
	/**
	 * 获取相互关注列表
	 * @author    zhangwei    2016-12-23
	 * @param    number $uid 用户ID
	 */
	public function friends($uid = 0) {
		$this->_getRelatedUsers('friends', $uid);
	}
	
	/**
	 * 获取关注列表
	 * @author    zhangwei    2016-12-24
	 * @param    number $uid 用户ID
	 */
	public function followed($uid = 0) {
		$this->_getRelatedUsers('followed', $uid);
	}
	
	/**
	 * 获取粉丝列表
	 * @author    zhangwei    2016-12-24
	 * @param    number $uid 用户ID
	 */
	public function fans($uid = 0) {
		$this->_getRelatedUsers('fans', $uid);
	}
	
	private function _getRelatedUsers($type = 'friends', $uid = 0) {
		//可获取特定用户uid的粉丝列表,没传入默认获取当前用户
		$uid = $this->userId;
		//TODO 如果获取非当前用户$this -> userId的粉丝列表,必需拥有超级权限$this -> super
		//TODO 获取当前用户的粉丝列表
		$relation_model = D('WeiboUserRelation');
		$weibo_user_model = D('WeiboUser');
		$where1 = array();
		switch ($type) {
			case 'friends' :
				//$where1['mutual'] = 1;
				//$where1['user_id'] = $uid;
				$friends_skip = I('post.friendsSkip');
				$friends_limit = I('post.friendsLimit');
				//$relation_result   = $relation_model -> where($where1) -> limit($friends_skip,$friends_limit) -> select();
				$uids = $relation_model->getFriends($uid, $friends_skip, $friends_limit);
				break;
			case 'followed' :
				//$where1['user_id'] = $uid;
				//$where1['mutual'] = 0;
				$followed_skip = I('post.followedSkip');
				$followed_limit = I('post.followedLimit');
				//$relation_result   = $relation_model -> where($where1) -> limit($followed_skip,$followed_limit) -> select();
				$uids = $relation_model->getFollowed($uid, $followed_skip, $followed_limit);
				break;
			case 'fans' :
				//$where1['follow'] = $uid;
				//$where1['mutual'] = 0;
				$fans_skip = I('post.fansSkip');
				$fans_limit = I('post.fansLimit');
				//$relation_result   = $relation_model -> where($where1) -> limit($fans_skip,$fans_limit) -> select();
				$uids = $relation_model->getFans($uid, $fans_skip, $fans_limit);
				break;
		}
		
		if ($uids) {

// 			foreach ($relation_result as $value){
// 				if($type == 'fans'){
// 					$uids[] = $value['user_id'];
// 				}else{
// 					$uids[] = $value['follow'];
// 				}
// 			}
			$avatar_list = \User\Lib\ImiLib::getAvatarByUserIds($uids); //获取头像列表
			$relations = D('WeiboUserRelation')->getRelationByUserids($this->userId, $uids);
			
			$where2['user_id'] = array('in', $uids);
			$weibo_user_result = $weibo_user_model->where($where2)->order('weibo_uid desc')->select();
			if ($weibo_user_result) {
				foreach ($weibo_user_result as &$value) {
					foreach ($avatar_list as $value2) {
						if ($value2['id'] == $value['user_id']) {
							$value['avatar'] = $value2['avatar'];
						}
					}
					foreach ($relations as $key3 => $value3) {
						if ($key3 == $value['user_id']) {
							$value['relations'] = $value3;
						}
					}
				}
				$assign['info'] = $weibo_user_result;
				$assign['msg'] = '成功';
			} else {
				$assign['error'] = 1;
				$assign['error_msg'] = '没有相关信息';
			}
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '没有相关信息';
			
		}
		$this->output($assign);
	}
	
	/**
	 * 关注某一用户
	 * @author    zhangwei    2016-12-24
	 * @param    number $target_uid 目标用户的ID
	 */
	public function follow($target_uid = 0) {
		$target_uid = I('post.target_uid');
		$uid = $this -> userId;
		$relation_model = D('WeiboUserRelation');
		$weibo_user_model = D('WeiboUser');
		// step 0 判断target_uid 用户是否存在 和是否是自己
		$weibo_user_result = $weibo_user_model->where('user_id = ' . $target_uid)->find();
		if (!$weibo_user_result || $target_uid == $uid) {
			$assign['error'] = 1;
			$assign['error_msg'] = '请勿非法操作';
		} else {
			// step1 判断是否已经关注过
			$follow_result = $relation_model->where('user_id =' . $uid . ' and follow =' . $target_uid)->find();
			if ($follow_result) {
				$assign['error'] = 1;
				$assign['error_msg'] = '您已经关注过了';
			} else {
				// step2 判断是否为相互关注关系,插入用户关系表信息
				$mutual_concern = $relation_model->where('user_id=' . $target_uid . ' and follow=' . $uid)->find();
				if ($mutual_concern) {  //判断是否为互相关注
					$data['mutual'] = 1;
					$target_mutual = $relation_model->where('user_id=' . $target_uid . ' and follow=' . $uid)->setField('mutual', 1); // 两用户成为相互关注关系
					if (!$target_mutual) {
						$err_msg = $relation_model->getError();
						weibo_log('[on:follow,step:2,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
					}
				}
				$data['user_id'] = $uid;
				$data['follow'] = $target_uid;
				// step3 添加关系表数据,并判断是否执行成功
				if ($relation_model->add($data)) {
					// step4 修改发起用户的关注数
					$res1 = $weibo_user_model->where('user_id=' . $uid)->setInc('follow_count');
					// step5  修改目标用户的粉丝数
					$res2 = $weibo_user_model->where('user_id=' . $target_uid)->setInc('fans_count');
					// step6 判断是否执行成功
					if ($res1 && $res2) {
						push_system_msg($target_uid, '有新的粉丝了~');
						$assign['msg'] = '关注成功';
						$assign['status'] = 1;
					} else {
						$err_msg = $weibo_user_model->getError();
						weibo_log('[on:follow,step:3,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
					}
				} else {
					$err_msg = $relation_model->getError();
					weibo_log('[on:follow,step:3,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
				}
			}
		}
		$this->output($assign);
	}
	
	/**
	 * 取消关注某一用户
	 * @author    zhangwei    2016-12-24
	 * @param    number $target_uid 目标用户的ID
	 */
	public function unfollow($target_uid = 0) {
		$relation_model = D('WeiboUserRelation');
		$weibo_user_model = D('WeiboUser');
//		$uid	= I('post.uid');
		$uid = $this->userId;
		// step1 查询是否存在此目标用户
		$relation_result = $relation_model->where('user_id=' . $uid . ' and follow=' . $target_uid)->find();
		if ($relation_result) {
			// step2 删除用户关系表,并判断是否执行成功
			if ($relation_model->delete($relation_result['rel_id'])) {
				//step3 判断相互关注,修改目标用户的相互关注字段
				if ($relation_result['mutual'] == 1) {
					$relation_model->where('user_id=' . $target_uid . ' and follow= ' . $uid)->setField('mutual', 0);
				}
				// step4 修改发起用户的关注数
				$res1 = $weibo_user_model->where('user_id=' . $uid)->setDec('follow_count');
				// step5 修改目标用户的粉丝数
				$res2 = $weibo_user_model->where('user_id=' . $target_uid)->setDec('fans_count');
				// step6 判断是否执行成功
				if ($res1 && $res2) {
					$assign['msg'] = '取消成功';
					$assign['status'] = 1;
				} else {
					$err_msg = $weibo_user_model->getError();
					weibo_log('[on:unfollow,step:6,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
				}
			} else {
				$err_msg = $relation_model->getError();
				weibo_log('[on:unfollow,step:2,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
			}
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '没有此用户';
		}
		$this->output($assign);
	}
	
	/**
	 * 获取黑名单
	 * @author    zhangwei    2016-12-24
	 * @param    number $uid 用户ID
	 */
	public function blacklist($uid = 0) {
		//可获取特定用户uid的黑名单,没传入默认获取当前用户
		$uid = $this->userId;
		$skip = I('post.skip');
		$limit = I('post.limit');
		//TODO 如果获取非当前用户$this -> userId的黑名单列表,必需拥有超级权限$this -> super
		if ($this->super) {
		}
		$blacklist_model = D('WeiboUserBlacklist');
		$weibo_user_model = D('WeiboUser');
		// step1 查询黑名单列表
		$blacklist = $blacklist_model->where('user_id=' . $uid)->limit($skip, $limit)->select();
		// step2 判断是否有数据
		if ($blacklist) {
			foreach ($blacklist as $black) {
				$black_uids[] = $black['target_id'];
			}
			$avatar_list = \User\Lib\ImiLib::getAvatarByUserIds($black_uids); //获取头像列表
			$where['user_id'] = array('in', $black_uids);
			// step3 查询对应的黑名单用户的微博用户信息
			$weibo_user_list = $weibo_user_model->where($where)->select();
			if ($weibo_user_list) {
				foreach ($weibo_user_list as &$value) {
					foreach ($avatar_list as $value2) {
						if ($value2['id'] == $value['user_id']) {
							$value['avatar'] = $value2['avatar'];
						}
					}
				}
				$assign['status'] = 1;
				$assign['msg'] = '成功';
				$assign['info'] = $weibo_user_list;
			} else {
				$err_msg = $weibo_user_model->getError(); //不输出
			}
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '没有相关数据';
		}
		$this->output($assign);
	}
	
	/**
	 * 添加到黑名单
	 * @author    zhangwei    2016-12-24
	 * @param    number $target_uid 目标用户的ID
	 */
	public function addToBlackList($target_uid = 0) {
		$uid = $this->userId;
		$relation_model = D('WeiboUserRelation');
		$blacklist_model = D('WeiboUserBlacklist');
		$weibo_user_model = D('WeiboUser');
		// step0 判断是否有此用户 和 是否是自己
		$weibo_user_result = $weibo_user_model->where('user_id = ' . $target_uid)->find();
		if (!$weibo_user_result || $target_uid == $uid) {
			$assign['error'] = 1;
			$assign['error_msg'] = '请勿非法操作';
		} else {
			// step1 判断是否已经在黑名单中
			$black_result = $blacklist_model->where('user_id=' . $uid . ' and target_id=' . $target_uid)->find();
			if (!$black_result) {
				$black_data['user_id'] = $uid;
				$black_data['target_id'] = $target_uid;
				// step 2 加入黑名单，并判断是否执行成功
				if ($blacklist_model->add($black_data)) {
					// step3 判断两者是否为相互关注关系
					$mutual_concern = $relation_model->where('user_id=' . $target_uid . ' and follow=' . $uid)->find();
					if ($mutual_concern) {
						// step3-1 组合发起用户和目标用户 关注数和粉丝数的数据
						$weibo_user_data1['follow_count'] = array('exp', 'follow_count-1');
						$weibo_user_data1['fans_count'] = array('exp', 'fans_count-1');
						$weibo_user_data2['follow_count'] = array('exp', 'follow_count-1');
						$weibo_user_data2['fans_count'] = array('exp', 'fans_count-1');
						// step3-2 删除发起用户-目标用户关系表  和  目标用户-发起用户的关系表
						$relation_res1 = $relation_model->where('user_id=' . $uid . ' and follow=' . $target_uid)->delete();
						$relation_res2 = $relation_model->where('user_id=' . $target_uid . ' and follow=' . $uid)->delete();
						if (!$relation_res1 || !$relation_res2) {
							$err_msg = $relation_model->getError();
							weibo_log('[on:addToBlackList,step:3-2,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
						}
					} else {
						// step3-1 组合发起用户的关注数， 和目标用户的粉丝数
						$weibo_user_data1['follow_count'] = array('exp', 'follow_count-1');
						$weibo_user_data2['fans_count'] = array('exp', 'fans_count-1');
						// step3-2 删除发起用户 - 目标用户关系表
						$relation_res1 = $relation_model->where('user_id=' . $uid . ' and follow=' . $target_uid)->delete();
						if (!$relation_res1) {
							$err_msg = $relation_model->getError();
							weibo_log('[on:addToBlackList,step:3-2,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
						}
					}
					// step4 更改发起用户 和关注用户的关注数 和粉丝数
					$weibo_user_res1 = $weibo_user_model->where('user_id=' . $uid)->save($weibo_user_data1);
					$weibo_user_res2 = $weibo_user_model->where('user_id=' . $target_uid)->save($weibo_user_data2);
					if (!$weibo_user_res1 || !$weibo_user_res2) {
						$err_msg = $relation_model->getError();
						weibo_log('[on:addToBlackList,step:4,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
					}
					// step5  设置拉黑成功状态
					$assign['msg'] = '拉黑成功';
					$assign['status'] = 1;
				} else {
					$err_msg = $relation_model->getError();
					weibo_log('[on:addToBlackList,step:5,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
				}
			} else {
				$assign['error'] = 1;
				$assign['error_msg'] = '已经拉黑';
			}
		}
		$this->output($assign);
	}
	
	/**
	 * 从黑名单中移除
	 * @param    number $target_uid 目标用户的ID
	 */
	public function delFromBlackList($target_uid = 0) {
		$uid = $this->userId;
		$blacklist_model = D('WeiboUserBlacklist');
		// step1 判断目标用户是否在黑名单中
		$black_result = $blacklist_model->where('user_id=' . $uid . ' and target_id=' . $target_uid)->find();
		if ($black_result) {
			// step2 移除此黑名单
			$del_black = $blacklist_model->where('user_id=' . $uid . ' and target_id=' . $target_uid)->delete();
			// step3 判断是否执行成功
			if ($del_black) {
				$assign['msg'] = '移除成功';
				$assign['status'] = 1;
			} else {
				$err_msg = $blacklist_model->getError();
				weibo_log('[on:addToBlackList,step3:,target:' . $target_uid . ',uid:' . $uid . ',err_msg' . $err_msg . ']');
			}
		} else {
			$assign['error'] = 1;
			$assign['error_msg'] = '没有此黑名单列表';
		}
		
		$this->output($assign);
	}
	
	/**
	 * 获取用户信息接口
	 * @author    Baiyu
	 * @param    number $user_id 用户ID或ID数组
	 * @param    string $getImage 是否同时获取用户的图片数据(微博图片),只有获取单个用户数据时可用
	 */
	public function userInfo($user_id = 0, $get_image = FALSE, $get_relation = TRUE) {
		
		//申明变量
		$error = 0;
		$error_msg = '';
		$original_user = array();
		$user = array();
		$multi = strpos($user_id, ',');
		
		//查出用户
		if ($multi) {
			$user_id = explode(',', $user_id);
			$user = D('WeiboUser')->getUserByIds($user_id);
		} else {
			$user = D('WeiboUser')->getUserById($user_id);
		}
		if (FALSE === $user) {
			$error = 101;
			$error_msg = '操作失败';
		} elseif (empty($user)) {
			$error = 102;
			$error_msg = '没有这个用户';
		} else {
			if ($multi) {
				$original_user = translate_field('User', \User\Lib\ImiLib::getUserByIds($user_id));
				foreach ($original_user as $item) {
					$user[$item['user_id']] = array_merge($user[$item['user_id']], $item);
				}
			} else {
				$original_user = translate_field('User', \User\Lib\ImiLib::getUserById($user_id));
				$user = array_merge($original_user, $user);
			}
		}
		
		//查出用户图片
		if (!$multi && $get_image && !empty($user)) {
			$user['images'] = D('WeiboAttachment')->getUserPictures($user_id, 5);
		}
		
		//查出用户关系
		if (!$multi && $get_relation) {
			$user['relations'] = D('WeiboUserRelation')->getRelationByUserids($this->userId, $user_id);
			$user['inBlackList'] = intval(D('WeiboUserBlacklist')->inBlacklist($this->userId, $user_id));
		}
		
		$assign['error'] = $error;
		$assign['error_msg'] = $error_msg;
		$assign['status'] = intval(!$error);
		$assign['user'] = $user;
		$this->output($assign);
		
	}
	
	/**
	 * 获取关系通过用户ID或ID数组
	 * @author    Baiyu
	 * @param    number $user_ids 用户ID或用户ID组成的js数组生成的JSON字符串
	 */
	public function userRelation($user_ids = 0) {
		
		//申明变量
		$error = 0;
		$error_msg = '';
		$relations = array();
		
		//如果不是数字那么是json字符串的数组
		!is_numeric($user_ids) && $user_ids = json_decode($user_ids, TRUE);
		
		//判断是否为空或为0
		if (empty($user_ids)) {
			$error = 101;
			$error_msg = '传入用户ID不合法';
		}
		
		//获取数据
		if (!$error) {
			$relations = D('WeiboUserRelation')->getRelationByUserids($this->userId, $user_ids);
		}
		
		//输出结果
		$assign['error'] = $error;
		$assign['error_msg'] = $error_msg;
		$assign['relations'] = $relations;
		
		$this->output($assign);
	}
	
	//选择关注用户列表
	public function selectFollowedUserList() {
		$uid = $this->userId;
//		$this -> userId =10;
//		$uid = 10;
		$relation_model   = D('WeiboUserRelation');
		$weibo_user_model = D('WeiboUser');
		$uids = $relation_model -> getFollowed($uid);
		if($uids){
			$avatar_list = \User\Lib\ImiLib::getAvatarByUserIds($uids); //获取头像列表
			$where2['user_id'] = array('in', $uids);
			$weibo_user_result = $weibo_user_model->where($where2)->select();
			$pinyin = new PinYin();
			if ($weibo_user_result) {
				$res = array();
				foreach ($weibo_user_result as $value){
					foreach ($avatar_list as $value2) {
						if ($value2['id'] == $value['user_id']) {
							$value['avatar'] = $value2['avatar'];
						}
					}
					$firstChar  = $pinyin -> getFirstChar($value['nickname']);
					$value['firstChar'] = $firstChar;
					$res[$firstChar][] = $value;
				}
				ksort($res); // 按照key值进行排序
				$assign['info'] = $res;
				$assign['msg'] = '成功';
			}
		}else{
			$assign['error'] = 1;
			$assign['error_msg'] = '没有关注列表';
		}
		$this -> output($assign);
	}
}